import React, { Component } from 'react'
import WrapperNormalForm from './modal_form'
import WrapperNextForm from './register_step'
import { Form, Input, Button, Modal, message } from 'antd'
import axios from '../Utils/axios'
import cookie from 'js-cookie'
import url from 'url'
import Crypto from 'crypto-js'



const FormItem = Form.Item
const { query } = url.parse(window.location.href, true)

class RegisterForm extends Component {
    constructor (props) {
        super(props)
        this.state = {
            loading: false,
            visible: false,
            nextVisible: false,
            stateTime: new Date().getTime(),
            flag: true,
            loginFlag: true
        }
    }

    _showNextModal = val => {
        Modal.destroyAll()
        this.setState({
            nextVisible: true,
            userName: val
        })
    }

    _showVisible = val => {
        this.setState({
            visible: true
        })
        Modal.destroyAll()
    }

    _handlerLogin = e => {
        e.preventDefault()
        message.destroy()
        const { agreeStatus, standStatus } = this.props
        this.props.form.validateFieldsAndScroll((err, values) => {
          if (!err) {
              if(!agreeStatus) {
                  message.error('请勾选同意汇升投资《用户服务协议》及《隐私保护指引》')
                  return
              }
              if(!standStatus) {
                message.error('请勾选符合特定的合格投资者条件')
                return
            }
            message.loading('Loading...', 20)

            if (!this.state.flag) {
                return
            }
            this.setState({flag: false})
            axios({
              method: 'post',
              url: '/api/sso/account/loginUser',
              data: JSON.stringify({...values, imgtoken: this.state.imageToken })
            })
            .then(data => {
                message.destroy()

                if (data.status !== 'success') {
                    message.error(data.errorReason || data.reason)
                    this._getImagCode()
                    this.setState({flag: true})
                    return
                }
                if (!data.hasOwnProperty('result') || data.result ==='') {
                    message.info('接口获取数据失败')
                    this.setState({flag: true})
                    return
                }
                data = JSON.parse(data.result)

                if (data.result === 'success') {
                    this.setState({flag: true})
                    message.success(data.reason)
                    if (data.functionPermission.length > 0) {
                        window.localStorage.setItem('permission', JSON.stringify(data.functionPermission))
                    }
                    window.localStorage.setItem('userInfo', JSON.stringify({userName: data.userName ? data.userName : ''}))
                    cookie.set('token', data.token)
                    if (query.redirect) {
                        const redirectQuery = url.parse(decodeURIComponent(Crypto.enc.Base64.parse(query.redirect).toString(Crypto.enc.Utf8)), true)
                        if (Object.keys(redirectQuery.query).length > 0) {
                            window.location.href = `${decodeURIComponent(Crypto.enc.Base64.parse(query.redirect).toString(Crypto.enc.Utf8))}&token=${data.token}`
                        } else {
                            window.location.href = `${decodeURIComponent(Crypto.enc.Base64.parse(query.redirect).toString(Crypto.enc.Utf8))}?token=${data.token}`
                        }

                    } else {
                        // this.props.history.push('/home')
                        window.location.href = '/home/home'
                    }
                } else {
                    this._getImagCode()
                    this.setState({flag: true})
                    message.error(data.reason || '获取图片失败')
                }
            })
          }
        })
      }

    _getImagCode = () => {
        axios({
          method: 'post',
          url: '/api/sso/account/imgCode'
        })
        .then(data => {

        if (data.status !== 'success') {
            message.error(data.errorReason)
            return
        }

        if (!data.hasOwnProperty('result') || data.result ==='') {
            message.info('接口获取数据失败')
            return
        }
        data = JSON.parse(data.result)
          if (data && data.result === 'success') {
            this.setState({
                codeImage: data.imaCode,
                imageToken: data.imgtoken
              })
          } else {
            message.error(data.reason || '获取图片失败')
          }
        })
      }

    _goRegister = () => {
          axios({
            method: 'post',
            url: '/api/sso/account/imgCode'
          })
          .then(data => {
            if (data.status !== 'success') {
                message.error(data.errorReason)
                return
            }
            if (!data.hasOwnProperty('result') || data.result ==='') {
                message.info('接口获取数据失败')
                return
            }
            data = JSON.parse(data.result)
              if (data.result === 'success') {
                this.setState({
                    nextImage: data.imaCode,
                    imageToken: data.imgtoken
                  })
                  this.setState({
                      visible: true
                    })
              } else {
                message.error(data.reason || '获取图片失败')
              }

          })

    }

    _oncancelModal = () => {
        Modal.destroyAll()
        this.setState({
            visible: false,
            nextVisible: false
        })
    }


    componentDidMount () {
        this._getImagCode()
        document.addEventListener('keyup', (e) => {
            const codeType = e.keyCode
            if (codeType === 13 || e.key === 'Enter' || e.code === 'Enter') {
                this._handlerLogin(e)
            }
        }, false)
    }

    handlerValidate = (rule, value, callback) => {
        callback()
    }

    render () {
        const { visible, nextVisible } = this.state

        const { getFieldDecorator } = this.props.form

        return (
            <div>
                <Form className="login-form login_wrapper" onSubmit={this._handlerLogin}>
                    <FormItem>
                        {
                            getFieldDecorator('username', {
                                rules: [{
                                    message: '用户名不能为空！',
                                    required: true
                                },
                                {
                                    validator: (rule, value, callback) => this.handlerValidate(rule, value, callback)
                                }]
                            })(
                                <Input
                                className="user-input-default"
                                type="text"
                                autoComplete="off"
                                prefix={<span className="user-label">用户名：</span>}
                                allowClear={true}
                                placeholder="请输入用户名"
                                />
                            )
                        }
                    </FormItem>

                    <FormItem>
                        {
                            getFieldDecorator('password',
                            {
                                rules: [{
                                    message: '用户密码不能为空！',
                                    required: true
                                }]
                            })(
                                <Input.Password
                                className="user-input-default"
                                type="password"
                                readOnly={true}
                                allowClear={true}
                                onFocus={this.removeReadOnly.bind(this)}
                                autoComplete={'old-password'}
                                prefix={<span className="user-label">密&nbsp;&nbsp;&nbsp;&nbsp;码：</span>}
                                placeholder="请输入用户密码" />
                            )
                        }
                    </FormItem>

                    <FormItem className='clear-fix'>
                        {
                            getFieldDecorator('imgCode', {
                                rules: [{
                                    message: '图形验证码不能为空',
                                    required: true
                                }]
                            })(
                                <Input
                                maxLength={6}
                                autoComplete={'off'}
                                className='image-code first-login-img'
                                allowClear={true}
                                prefix={<span className="user-label">验证码：</span>}
                                placeholder="请输入图形验证码" />
                            )
                        }
                        <div className='image-validate'>
                            <img src={this.state.codeImage ? 'data:image/png;base64,'+this.state.codeImage : ''} alt="" onClick={() => {this._getImagCode()}} />
                        </div>
                    </FormItem>

                    <FormItem>
                            <Button htmlType="submit" className="login-submit" type="primary">登录</Button>
                            <p className="link-register">&nbsp;</p>
                            {/* <p className="link-register">没有账号?点击<span onClick={() => { this._goRegister() }}>注册</span><a href='/forgetPass' className={`forget_password`}>
                                <Icon type={`exclamation`} className={`info_forget`} />忘记密码？</a></p> */}
                    </FormItem>
                </Form>

                <Modal
                visible={ visible }
                title="注册"
                centered
                onOk={this._oncancelModal}
                className="login_register"
                onCancel={this._oncancelModal}
                destroyOnClose={true}
                footer={null}>
                    <WrapperNormalForm {...this.state}  hideModal={this._oncancelModal} showNext={this._showNextModal.bind(this)}/>
                </Modal>

                <Modal
                title="注册"
                onOk={this._oncancelModal}
                onCancel={this._oncancelModal}
                footer={null}
                centered
                className="login_register"
                destroyOnClose={true}
                visible={nextVisible}>
                    <WrapperNextForm {...this.state} hideModal={this._oncancelModal} showVisible={this._showVisible.bind(this)} />
                </Modal>
        </div>
        )
    }

    removeReadOnly (e) {
        console.log(e.target.removeAttribute('readonly'))
    }
}

const ComForm = Form.create({ name: 'login-form' })(RegisterForm)

export default ComForm
